package com.vd.wmt.process.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.vd.wmt.model.Status;
import com.vd.wmt.model.WageDetail;
import com.vd.wmt.parse.BeanToXmlParse;
import com.vd.wmt.parse.PropParse;
import com.vd.wmt.process.ProcessCallBack;
import com.vd.wmt.process.SendProcess;
/**
 * @desc 邮件发送处理
 * @author tudongyun
 *
 */
public class MailSendProcess implements SendProcess {

	public MailSendProcess() {
		
	}

	private String senderUser;
	private String senderPasswd;
	private Log log = LogFactory.getLog(MailSendProcess.class);
	private Status status = Status.INIT;
	private String errMsg;
	private List<WageDetail> wageList;
	private ProcessCallBack callBack;
	private Integer sendPos = 0;

	@Override
	public void SendMsg(List<WageDetail> list,String user, String passwd) {
		
		SendMsg(list, null,user,passwd);
	}
	@Override
	public void SendMsg(List<WageDetail> list, ProcessCallBack callBack,String user, String passwd) {
		log.info("sendMsg start....");
		this.status = Status.SENDING;
		this.wageList = list;
		this.callBack = callBack;
		this.senderUser = user;
		this.senderPasswd = passwd;
		doSend();
		log.info("sendMsg end......");
	}

	private void doSend() {
		Integer threadCount = Integer.valueOf(PropParse.getInstance().getValue("vd.send.threads"));
		Thread[] threadGroup = new Thread[threadCount];
		SendTask sendTask = new SendTask();
		for(int i=0;i<threadCount;i++){
			threadGroup[i] = new Thread(sendTask,"sendMail-Thread-"+i);
			threadGroup[i].start();
		}
		Thread afterThread = new Thread(new AfterSendTask(threadGroup),"afterSendMail-Thread");
		afterThread.start();
		//callBack.tipMsg("邮件正在发送.....");
	}

	@Override
	public String getError() {
		return errMsg;
	}

	@Override
	public Status getStatus() {
		return status;
	}

	protected class SendTask implements Runnable {
		@Override
		public void run() {
			log.info(Thread.currentThread().getName()+"start.....");
			boolean running = true;
			Integer sendCnts = wageList.size();
			Session session = Session.getDefaultInstance(PropParse.getInstance().getProp(), new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(senderUser, senderPasswd);
				}
			});
			BeanToXmlParse parse = BeanToXmlParse.getInstance();
			while (running) {
				WageDetail wd = null;
				synchronized (sendPos) {
					if (sendPos < sendCnts) {
						log.info("send pos:" + sendPos);
						wd = wageList.get(sendPos);
						sendPos++;
					} else {
						running = false;
						break;
					}
				}
				if (wd == null) {
					log.warn("工资单为空");
					continue;
				}
				log.info(Thread.currentThread().getName()+"send ["+sendPos+"] start");
				try {
					wd.setStatus(Status.SENDING);
					if(callBack != null)callBack.exec(wd);
					String month = new SimpleDateFormat("yyyy年MM月").format(wd.getYearMonth());
					parse.putArgs("wage", wd, null);
					parse.putArgs("month", month, null);
					String content = parse.parse("mail.vm");
					Message msg = new MimeMessage(session);
					InternetAddress addressFrom = new InternetAddress(senderUser
							+ PropParse.getInstance().getValue("vd.mail_suffix"));
					msg.setFrom(addressFrom);
					msg.setRecipient(Message.RecipientType.TO, new InternetAddress(wd.getEmail()));

					msg.setSubject(month + "份工资条");
					msg.setContent(content, "text/html;charset=gb2312");
					msg.setSentDate(new Date());
					Transport.send(msg);
					wd.setStatus(Status.SUCC);
					if(callBack != null)callBack.exec(wd);
				} catch (Exception e) {
					log.error("send mail Exception", e);
					wd.setStatus(Status.FAILD);
					if(callBack != null)callBack.exec(wd);
				}
				log.info(Thread.currentThread().getName()+"send ["+sendPos+"] end");
			}
		}
	}
	protected class AfterSendTask implements Runnable{
		private Thread[] group;
		public AfterSendTask( Thread[] group) {
			this.group=group;
		}
		@Override
		public void run() {
			log.info("AfterSendTask start....");
			for(Thread thread: group){
				try {
					thread.join();
				} catch (InterruptedException e) {
					log.error("waitException", e);
				}
			}
			status=Status.COMP;
			if(callBack != null)callBack.tipMsg("邮件发送已完成完成。\n标红为发送失败");
		}
		
	}

}
